import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:flutterproject/mvvm/base/base_controller.dart';
import 'package:flutterproject/page/setting/children/upgrade/data/upgrade_bean.dart';
import 'package:flutterproject/util/address_manager.dart';
import 'package:flutterproject/util/dialog_toast/dialog_util.dart';
import 'package:flutterproject/util/dialog_toast/toast_util.dart';
import 'package:flutterproject/util/extension/extension_util.dart';
import 'package:flutterproject/util/http/http_client.dart';
import 'package:flutterproject/util/http/http_exception.dart';
import 'package:flutterproject/util/margin_padding_util.dart';
import 'package:flutterproject/widget/button_common.dart';
import 'package:flutterproject/widget/image_extended.dart';
import 'package:flutterproject/widget/text/text_common.dart';
import 'package:get/get.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:r_upgrade/r_upgrade.dart';

class UpgradeController extends BaseController {
  HttpClient client = Get.find<HttpClient>();
  String version = "";

  UpgradeBean? upgradeBean = UpgradeBean();
  SmartDialogController smartDialogController = SmartDialogController();

  int? id;

  double percent = 0;

  @override
  void onReady() {
    super.onReady();
    getVersion();
    RUpgrade.stream.listen((DownloadInfo info) {
      if (info.status == DownloadStatus.STATUS_SUCCESSFUL) {
        DialogUtil.dismiss();
        return;
      }
      percent = info.percent ?? 0;
      setState1(() {});
    });
  }

  Future checkUpgrade() async {
    try {
      DialogUtil.showLoading();
      upgradeBean = await client.get<UpgradeBean>(AddressManager.upgrade);
      PackageInfo packageInfo = await PackageInfo.fromPlatform();
      if (int.parse(packageInfo.buildNumber) <
          int.parse(upgradeBean?.versionCode ?? "10000")) {
        showUpgradeDialog();
      }
      return true;
    } on HttpException catch (e) {
      ToastUtil.showFailed(e.message);
      return false;
    } finally {
      DialogUtil.dismiss();
    }
  }

  Future getVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    version = packageInfo.version;
    update(['version']);
  }

  void showUpgradeDialog() {
    DialogUtil.showCustomDialog(
        Container(
          margin: MarginPaddingUtil.symmetric(horizontal: 80),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(10.radius),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                width: Get.width,
                height: 174.width,
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage('assets/image/main_bg.png'),
                    fit: BoxFit.fill, // 完全填充
                  ),
                ),
                child: Stack(
                  clipBehavior: Clip.none,
                  children: [
                    Positioned(
                      left: 57.width,
                      top: 57.width,
                      child: TextCommon(
                        "有新版本\n请更新体验",
                        size: 32.sp,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    Positioned(
                      right: 0,
                      top: -60.width,
                      child: ImageCommon(
                        "/image/ic_set1",
                        size: 211.width,
                      ),
                    )
                  ],
                ),
              ),
              55.heightBox,
              TextCommon(
                upgradeBean?.tips ?? "",
                color: Color(0xFF707785),
                maxLines: 10,
                size: 24.sp,
                lineHeight: 40.sp,
              ),
              175.heightBox,
              ButtonCommon(
                text: "更新",
                onTap: () async {
                  id = await RUpgrade.upgrade(
                    upgradeBean?.apkUrl ?? "",
                    fileName: 'app-release.apk',
                  );
                  await DialogUtil.dismiss();
                  showPercent();
                },
                fontSize: 32.sp,
                fontColor: Colors.white,
                color: Color(0xFFEDC88B),
                borderRadios: 50,
                padding: MarginPaddingUtil.only(top: 25, bottom: 29),
                margin: MarginPaddingUtil.symmetric(horizontal: 48),
              ),
              78.heightBox
            ],
          ),
        ),
        alignment: Alignment.center);
  }

  late StateSetter setState1;
  void showPercent() {
    DialogUtil.showCustomDialog(StatefulBuilder(
      builder: (BuildContext context, StateSetter setState) {
        setState1 = setState;
        return Container(
            padding: MarginPaddingUtil.all(30),
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(30.radius)),
            child: TextCommon(
              "下载中...$percent%",
              size: 30.sp,
            ));
      },
    ),
        alignment: Alignment.center,
        controller: smartDialogController,
        backDismiss: false);
  }
}
